<template>
  <div class="selfCheckScrapRecord zy-content">
    <!-- 搜索区域 -->
    <div class="search clear">
      <div class="search-box-layout">
        <Row :gutter="24">
          <Col span="6">
            <p class="label">物料编码</p>
            <div class="ipt">
              <Input v-model="searchParams.materialCode" placeholder="请输入物料编码" clearable/>
            </div>
          </Col>
          <Col span="6">
            <p class="label">物料名称</p>
            <div class="ipt">
              <Input v-model="searchParams.materialName" placeholder="请输入物料名称" clearable/>
            </div>
          </Col>
          <Col span="6">
            <div>
              <p class="label hide-label">--</p>
              <div class="ipt">
                <Button type="primary" class="search-btn" @click="handleSearch">搜索</Button>
                <Button class="reset-btn" @click="resetSearch">重置</Button>
              </div>
            </div>
          </Col>
        </Row>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>
        <Button @click="showAddModal" style="color: #fff!important;">新增</Button>
      </div>

      <!-- 表格区域 -->
      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            :columns="columns"
            ellipsis
            ref="selection"
            stripe
            :data="tableData"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="showDetail(row)"><i class="iconfont zy-common-chakan"></i>模具</span>
            <span class="operationBtn" @click="editRow(row)"><i class="iconfont zy-common-bianji"></i>编辑</span>
            <span class="operationBtn" @click="delRow(row)"><i class="iconfont zy-common-shanchu"></i>{{
                $t('common.Delete')
              }}</span>
          </template>
        </Table>
      </div>

      <!-- 分页 -->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectedIds.length"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="pageSizeOption"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>

    <!-- 新增/编辑模态框 -->
    <Modal
        v-model="modalVisible"
        :title="modalTitle"
        width="800"
        @on-cancel="resetForm"
    >
      <Form ref="form" :model="formData" :label-width="120">
        <Row :gutter="16">
          <Col span="24">
            <FormItem label="物料" prop="materialId">
              <Select
                  v-model="formData.materialId"
                  filterable
                  clearable
                  remote
                  :remote-method="handleMaterialRemote"
                  :loading="materialLoading"
                  placeholder="请输入物料编码或名称搜索"
                  @on-change="onMaterialChange"
              >
                <Option
                    v-for="item in materialList"
                    :value="item.id"
                    :key="item.id"
                >{{ item.materialCode }} - {{ item.materialName}}</Option>
              </Select>
              <div v-if="materialError" class="error-tip">{{ materialError }}</div>
            </FormItem>
          </Col>

          <Col span="24">
            <FormItem label="模具列表">
              <div class="mold-container">
                <div v-for="(mold, index) in formData.moldCodes" :key="index" class="mold-row">
                  <Select
                      v-model="formData.moldCodes[index]"
                      filterable
                      clearable
                      remote
                      :remote-method="handleMoldRemote"
                      :loading="moldLoading"
                      placeholder="请输入模具号搜索"
                      style="width: 85%; margin-right: 10px;"
                  >
                    <Option
                        v-for="item in moldList"
                        :value="item.moldCode"
                        :key="item.moldCode"
                    >{{ item.moldCode }}</Option>
                  </Select>
                  <Button
                      v-if="index === 0"
                      type="primary"
                      icon="md-add"
                      @click="addMold"
                      style="margin-right: 5px;"
                  ></Button>
                  <Button
                      v-if="index > 0"
                      type="error"
                      icon="md-remove"
                      @click="removeMold(index)"
                  ></Button>
                </div>
              </div>
              <div v-if="moldError" class="error-tip">{{ moldError }}</div>
            </FormItem>
          </Col>
        </Row>
      </Form>

      <div slot="footer">
        <Button @click="modalVisible = false">{{ $t("common.Cancel") }}</Button>
        <Button type="primary" @click="submitForm" :loading="submitLoading">
          确认
        </Button>
      </div>
    </Modal>

    <!-- 删除确认弹框 -->
    <Modal :mask-closable="false" v-model="deleteShow" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.sureDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="deleteSure">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>

    <!-- 模具详情弹框 -->
    <Modal v-model="detailVisible" title="模具详情" width="600">
      <Table :columns="detailColumns" :data="detailData" border></Table>
      <div slot="footer">
        <Button type="primary" @click="detailVisible = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import fileDownload from "js-file-download";

export default {
  name: "materialMoldBinding",
  data() {
    return {
      materialList: [],
      moldList: [],
      materialLoading: false,
      moldLoading: false,
      materialError: '',
      moldError: '',
      deleteShow: false,
      detailVisible: false,
      currentDeleteId: null,
      currentDetailId: null,
      // 搜索相关
      searchParams: {
        materialCode: '',
        materialName: '',
        moldCode: ''
      },

      // 表格相关
      columns: [
        {type: "selection", width: 60, align: "center"},
        {title: "物料编码", key: "materialCode", minWidth: 150, align: "center"},
        {title: "物料名称", key: "materialName", minWidth: 150, align: "center"},
        {
          title: "模具数量",
          key: "moldCount",
          minWidth: 120,
          align: "center",
          render: (h, {row}) => {
            const moldCodes = row.moldCodes || [];
            return h('span', moldCodes.length);
          }
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 250, // 加大操作列宽度
          align: "center"
        }
      ],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pageSizeOption: [10, 20, 30, 50],
      selectedIds: [],

      // 详情表格列
      detailColumns: [
        {title: "序号", type: "index", width: 80, align: "center"},
        {title: "模具号", key: "moldCode", align: "center"},
      ],
      detailData: [],

      // 表单相关
      modalVisible: false,
      modalTitle: "新增物料模具绑定",
      submitLoading: false,
      isEdit: false,
      currentId: null,

      formData: {
        materialId: "",
        moldCodes: [""]
      }
    };
  },

  mounted() {
    this.getList();
    this.handleMaterialRemote('');
    this.handleMoldRemote('');
  },

  methods: {
    handleMaterialRemote(query) {
      this.materialLoading = true;
      return this.axios({
        method: 'POST',
        url: '/dms/material/page',
        data: {
          materialCodeOrMaterialName: query,
          pageNum: 1,
          pageSize: 20
        }
      }).then(res => {
        if (res.code === 200) {
          this.materialList = res.data.records;
          // 编辑模式下确保当前选中的物料在列表中
          if (this.isEdit && this.formData.materialId) {
            const selectedMaterial = this.materialList.find(item => item.id === this.formData.materialId);
            if (!selectedMaterial) {
              this.materialList.unshift({
                id: this.formData.materialId,
                materialCode: this.formData.materialCode,
                materialName: this.formData.materialName
              });
            }
          }
        } else {
          this.$Message.warning({content: res.msg, duration: 6, closable: true});
        }
      }).finally(() => {
        this.materialLoading = false;
      });
    },

    handleMoldRemote(query) {
      this.moldLoading = true;
      return this.axios({
        method: 'POST',
        url: '/dms/moldinfo/getDeviceTzList',
        data: {
          moldCode: query,
          pageNum: 1,
          pageSize: 20
        }
      }).then(res => {
        if (res.code === 200) {
          this.moldList = res.data.records || [];
          // 编辑模式下确保当前选中的模具在列表中
          if (this.isEdit && this.formData.moldCodes) {
            this.formData.moldCodes.forEach(moldCode => {
              if (moldCode && !this.moldList.some(item => item.moldCode === moldCode)) {
                this.moldList.unshift({
                  moldCode: moldCode
                });
              }
            });
          }
        } else {
          this.$Message.warning({content: res.msg, duration: 6, closable: true});
        }
      }).finally(() => {
        this.moldLoading = false;
      });
    },

    // 物料选择变化
    onMaterialChange(materialId) {
      const selectedMaterial = this.materialList.find(item => item.id === materialId);
      if (selectedMaterial) {
        this.formData.materialCode = selectedMaterial.materialCode;
        this.formData.materialName = selectedMaterial.materialName;
      }
      this.materialError = '';
    },

    // 获取列表数据
    getList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      };

      this.axios({
        method: "POST",
        url: "/dms/basic/material/moldCode/list",
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list || [];
          this.total = res.data.total || 0;
        }
      });
    },

    // 搜索
    handleSearch() {
      this.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetSearch() {
      this.searchParams = {
        materialCode: '',
        materialName: '',
        moldCode: ''
      };
      this.handleSearch();
    },

    // 显示新增模态框
    showAddModal() {
      this.modalTitle = "新增物料模具绑定";
      this.isEdit = false;
      this.currentId = null;
      this.resetForm();
      this.modalVisible = true;
    },

    async editRow(row) {
      this.modalTitle = "编辑物料模具绑定";
      this.isEdit = true;
      this.currentId = row.id;

      // 重置表单确保干净状态
      this.resetForm();

      try {
        // 先加载基础数据
        await Promise.all([
          this.handleMaterialRemote(''),
          this.handleMoldRemote('')
        ]);

        // 使用$nextTick确保DOM更新完成
        this.$nextTick(() => {
          // 设置表单数据
          this.formData = {
            materialId: row.materialId,
            moldCodes: row.moldCodes ? [...row.moldCodes] : [""],
            materialCode: row.materialCode,
            materialName: row.materialName
          };


          this.modalVisible = true;
        });
      } catch (error) {
        console.error('加载编辑数据失败:', error);
        this.$Message.error('加载编辑数据失败');
      }
    },
    // 显示详情
    showDetail(row) {
      this.detailData = row.moldCodes.map(item => ({moldCode: item}));
      this.detailVisible = true;
    },

    // 删除确认
    delRow(row) {
      this.currentDeleteId = row.id;
      this.deleteShow = true;
    },

    // 确认删除
    deleteSure() {
      if (this.currentDeleteId) {
        this.axios({
          method: "DELETE",
          url: `/dms/basic/material/moldCode/delete`,
          data: [this.currentDeleteId]
        }).then(res => {
          if (res.code === 200) {
            this.$Message.success("删除成功");
            this.deleteShow = false;
            this.getList();
          } else {
            this.$Message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          this.$Message.error('删除失败: ' + (error.message || ''));
        });
      }
    },

    // 添加新的模具选择框
    addMold() {
      this.formData.moldCodes.push("");
    },

    // 移除模具选择框
    removeMold(index) {
      this.formData.moldCodes.splice(index, 1);
      this.moldError = '';
    },

    // 提交表单
    submitForm() {
      // 验证物料是否选择
      if (!this.formData.materialId) {
        this.materialError = '请选择物料';
        return;
      }

      // 验证模具是否选择
      const validMoldCodes = this.formData.moldCodes.filter(moldCode => moldCode && moldCode.trim() !== '');
      if (validMoldCodes.length === 0) {
        this.moldError = '请至少选择一个模具';
        return;
      }

      this.materialError = '';
      this.moldError = '';
      this.submitLoading = true;

      const formData = {
        materialId: this.formData.materialId,
        moldCodes: validMoldCodes
      };

      if (this.isEdit && this.currentId) {
        formData.id = this.currentId;
      }

      this.axios.post("/dms/basic/material/moldCode/add", formData).then(res => {
        if (res.code === 200) {
          this.$Message.success(this.isEdit ? "修改成功" : "新增成功");
          this.modalVisible = false;
          this.getList();
        } else {
          this.$Message.error(res.msg || '操作失败');
        }
      }).catch(error => {
        this.$Message.error('操作失败: ' + (error.message || ''));
      }).finally(() => {
        this.submitLoading = false;
      });
    },

    // 导出数据
    exportData() {
      const params = {...this.searchParams};

      this.axios({
        method: "POST",
        url: "/dms/basic/material/moldCode/export",
        params,
        responseType: "blob"
      }).then(res => {
        fileDownload(res, `物料模具绑定关系.xlsx`);
      }).catch(error => {
        this.$Message.error('导出失败: ' + (error.message || ''));
      });
    },

    resetForm() {
      this.formData = {
        materialId: "",
        moldCodes: [""],
        materialCode: "",
        materialName: ""
      };
      this.materialError = '';
      this.moldError = '';
    },

    // 分页变化
    changePageNum(val) {
      this.pageNum = val;
      this.getList();
    },

    changePageSize(val) {
      this.pageSize = val;
      this.getList();
    },

    // 表格选择变化
    onSelectChange(selection) {
      this.selectedIds = selection.map(item => item.id);
    },
  }
};
</script>

<style scoped lang="scss">
.materialMoldBinding {
  .search-area {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }

  .ivu-form-item {
    margin-bottom: 16px;
  }

  .ivu-col {
    display: flex;
    flex-direction: column;
  }

  .ivu-form-item-content {
    flex: 1;
  }

  .operationBtn {
    margin: 0 8px;  /* 增加按钮间距 */
    cursor: pointer;
    color: #2d8cf0;
    white-space: nowrap; /* 防止按钮换行 */

    &:hover {
      text-decoration: underline;
    }
  }

  .ivu-table-cell {
    padding: 12px 8px;
  }

  .mold-container {
    width: 100%;

    .mold-row {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .error-tip {
    color: #ed4014;
    margin-top: 5px;
  }
}
</style>